/**
 * 
 */
package cn.com.xf.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * Http连接工具类
 * 
 * @author fangjinsong
 * 
 */
public class HttpUtils {

	public final static String CHARSET_UTF8 = "UTF-8";
	public final static String CHARSET_GBK = "gbk";
	public final static String CHARSET_GB2312 = "gb2312";

	public static void main(String args[]) {
		String url = "http://www.baidu.com/s?wd=%E5%BA%9F%E7%89%A9%E7%82%B9%E5%BF%83&rsv_bp=0&ch=&tn=baidu&bar=&rsv_spt=3&ie=utf-8&rsv_sug3=2&rsv_sug=0&rsv_sug1=2&rsv_sug4=105&inputT=2959";
		String page = HttpUtils.getHtmlByUrl(url);
		System.out.println(page);
	}

	public static String getHtmlByUrl(String url) {
		URL u = parseUrl(url);
		String host = u.getHost();
		String path = u.getPath();
		String protocol = u.getProtocol();
		int port = 80;
		String query = u.getQuery();

		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(host, port, protocol);
		// client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
		// setProxy(client);

		HttpMethod getMethod = new GetMethod();
		getMethod.setPath(path);
		getMethod.setQueryString(query);
		// getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");

		try {
			client.executeMethod(getMethod);
			InputStream is = getMethod.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET_UTF8));
			StringBuffer sbf = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sbf.append(line);
			}
			br.close();
			getMethod.setRequestHeader("Connection", "close");
			return sbf.toString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getHtmlByUrl(String url, String responseCharset) {
		URL u = parseUrl(url);
		String host = u.getHost();
		String path = u.getPath();
		String protocol = u.getProtocol();
		int port = u.getPort();
		String query = u.getQuery();

		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(host, port, protocol);
		HttpMethod getMethod = new GetMethod();
		getMethod.setPath(path);
		getMethod.setQueryString(query);
		try {
			client.executeMethod(getMethod);
			InputStream is = getMethod.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, responseCharset));
			StringBuffer sbf = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sbf.append(line);
			}
			br.close();
			getMethod.setRequestHeader("Connection", "close");
			return sbf.toString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getHtmlByPostUrl(String url) {
		URL u = parseUrl(url);
		String host = u.getHost();
		String path = u.getPath();
		String protocol = u.getProtocol();
		int port = 80;
		String query = u.getQuery();
		String id = getId(query);

		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(host, port, protocol);
		HttpMethod postMethod = new PostMethod();
		try {
			client.executeMethod(postMethod);
			InputStream is = postMethod.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET_UTF8));
			StringBuffer sbf = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sbf.append(line);
			}
			br.close();
			postMethod.setRequestHeader("Connection", "close");
			return sbf.toString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String getTBHtmlByPostUrl(String url2) {
		HttpClient client = new HttpClient();
		String url = "http://item.taobao.com/item.htm";
		PostMethod method = new PostMethod(url);
		NameValuePair[] data = { new NameValuePair("id", "18578613535") };
		method.setRequestBody(data);
		try {
			int statusCode = client.executeMethod(method);
			System.out.println("请求结果-------" + statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				InputStream is = method.getResponseBodyAsStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET_UTF8));
				StringBuffer sbf = new StringBuffer();
				String line = null;
				while ((line = br.readLine()) != null) {
					sbf.append(line);
				}
				br.close();
				method.setRequestHeader("Connection", "close");
				return sbf.toString();
			} else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
				Header locationHeader = method.getResponseHeader("location");
				String location = null;
				if (locationHeader != null) {
					location = locationHeader.getValue();
					System.out.println("The page was redirected to:" + location);
				} else {
					System.err.println("Location field value is null.");
				}
			}

		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 解析路径为一个URL对象
	 * 
	 * @param s
	 * @return
	 */
	private static URL parseUrl(String s) {
		URL url = null;
		try {
			url = new URL(s);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return url;
	}

	private static void setProxy(HttpClient client) {
		client.getHostConfiguration().setProxy("192.168.16.189", 8080);
		client.getParams().setAuthenticationPreemptive(true);
		UsernamePasswordCredentials creds = new UsernamePasswordCredentials("fangjinsong", "fang2018");
		client.getState().setProxyCredentials(AuthScope.ANY, creds);
	}

	private static String getId(String query) {
		String result = "";
		String params[] = query.split("&");
		for (int i = 0; i < params.length; i++) {
			String param = params[i];
			if (param.startsWith("id=")) {
				result = param;
			}
		}
		return result;
	}
}
